<script setup>
import { updateAllocateRolesAsync } from '@/api/userManagement';
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  rolesInfo: {
    type: Object,
    default: {}
  }
})

const emit = defineEmits(['closeRolesDialog'])
//所有角色
const rolesList = ref()
//已有角色
const hasRole = ref()
const userId = computed(() => props.rolesInfo.userId)

const handleClose = () => {
  emit('closeRolesDialog', false)
}

const handleReset = () => {
  rolesList.value = props.rolesInfo.roles.map(item => {
    return {
      key: item.id,
      label: item.roleName
    }
  })
  hasRole.value = props.rolesInfo.roleIds || []
}

//保存/更新
const handleUpdate = async () => {
  try {
    const params = {
      userId: userId.value,
      roleIds: hasRole.value,
    }
    const res = await updateAllocateRolesAsync(params)
    console.log('%c [  ]-46', 'font-size:13px; background:pink; color:#bf2c9f;', res)
    if (res && res.code + '' === '200') {
      emit('closeRolesDialog', true)
    }

  } catch (error) {
    console.log('%c [ error ]-41', 'font-size:13px; background:pink; color:#bf2c9f;', error)

  }
}

const dialogVisible = computed(() => props.visible)


watch(() => props.rolesInfo, () => {
  handleReset()
})

</script>


<template>
  <div class="dialog-container">
    <el-dialog v-model="dialogVisible" title="分配角色" width="700" :before-close="handleClose" align-center
      :close-on-click-modal="false" :close-on-press-escape="false" :center="true" :destroy-on-close="true">

      <div class="transfer">
        <el-transfer v-model="hasRole" :data="rolesList" :titles="['可分配角色', '已有角色']" :button-texts="['撤回', '分配']" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="btn-blue" type="primary" @click="handleReset">
            重置
          </el-button>
          <el-button class="btn-green" type="primary" @click="handleUpdate">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.dialog-container {
  .transfer {
    margin: 0 auto;

    :deep(.el-transfer) {
      display: flex;
      align-items: center;
      justify-content: center;

      .el-transfer__buttons {
        padding: 0 20px;

        .el-button:nth-child(1) {
          background-color: #6ca9bb !important;
          transition: all 0.3s !important;

          &:hover {
            background-color: #7dd9eb !important;

          }
        }

        .el-button:nth-child(2) {
          background-color: #7dbb6c !important;
          transition: all 0.3s !important;

          &:hover {
            background-color: #8fdf3a !important;
          }
        }
      }
    }
  }
}

:deep(.el-button) {
  color: #fff;
  width: 100px;
  height: 35px;
  font-size: 16px;
  border-color: #c6c6c6;
}
</style>